package com.brsya.movie.activity;

import android.content.Context;
import android.graphics.Rect;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.DisplayMetrics;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.fragment.app.FragmentTransaction;

import com.brsya.base.base.BaseLayoutActivity;
import com.brsya.base.bean.MovieBean;
import com.brsya.base.util.StringUtil;
import com.brsya.base.util.UiUtil;
import com.brsya.movie.R;
import com.brsya.movie.fragment.SearchHistoryFragment;
import com.brsya.movie.fragment.SearchListFragment;

/**
 * Created by Brsya
 * CreateDate: 2022/7/7  15:35
 * Description:
 * 搜索页面
 */
public class SearchActivity extends BaseLayoutActivity implements View.OnClickListener {

    private LinearLayout llTitleBox;
    private LinearLayout llTitleBackBox;
    private EditText etSearchInput;
    private LinearLayout llSearchClear;
    private TextView tvSearchSubmit;
    private FrameLayout flSearchBox;
    private FrameLayout flSearchHistory;

    /**
     * 屏幕高度
     */
    private int heightPixels;
    /**
     * 输入法是否显示
     */
    private boolean imIsShow;

    private SearchListFragment searchListFragment;
    private SearchHistoryFragment searchHistoryFragment;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search);
        initView();

        initViewData();
    }


    private void initView() {
        llTitleBox = findViewById(R.id.ll_title_box);
        llTitleBackBox = findViewById(R.id.ll_title_back_box);
        etSearchInput = findViewById(R.id.et_search_input);
        llSearchClear = findViewById(R.id.ll_search_clear);
        tvSearchSubmit = findViewById(R.id.tv_search_submit);
        flSearchBox = findViewById(R.id.fl_search_box);
        flSearchHistory = findViewById(R.id.fl_search_history);
    }

    private void initViewData() {
        UiUtil.setStatusPadding(this, llTitleBox);

        llTitleBackBox.setOnClickListener(this);
        tvSearchSubmit.setOnClickListener(this);
        llSearchClear.setOnClickListener(this);


        etSearchInput.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.length() > 0) {
                    llSearchClear.setVisibility(View.VISIBLE);
                }else{
                    llSearchClear.setVisibility(View.GONE);
                    // 显示搜索历史
                    flSearchHistory.setVisibility(View.VISIBLE);
                    searchListFragment.clearData();
                }
            }
        });
        // 获取屏幕高度
        WindowManager manager = getWindowManager();
        DisplayMetrics outMetrics = new DisplayMetrics();
        manager.getDefaultDisplay().getMetrics(outMetrics);
        heightPixels = outMetrics.heightPixels;
        // 关闭输入法自动失去焦点
        etSearchInput.getViewTreeObserver().addOnGlobalLayoutListener(() -> {

            //获取当前根视图在屏幕上显示的大小
            Rect r = new Rect();
            etSearchInput.getWindowVisibleDisplayFrame(r);

            // 判断是否显示键盘
            if (heightPixels - r.bottom > 300) {
                imIsShow = true;
            }
            // 判断显示高度是否等于屏幕高度  键盘显示转为隐藏
            if (heightPixels == r.bottom && imIsShow) {
                imIsShow = false;
                etSearchInput.clearFocus();
            }
        });
        etSearchInput.requestFocus();

        etSearchInput.setOnEditorActionListener((textView, i, keyEvent) -> {
            // 搜索或回车
            if (i == EditorInfo.IME_ACTION_SEARCH || (keyEvent != null && keyEvent.getAction() == KeyEvent.KEYCODE_ENTER)) {
                search();
                return true;
            }
            return false;
        });

        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
        ft.add(R.id.fl_search_box, searchListFragment = SearchListFragment.newInstance(null));
        ft.add(R.id.fl_search_history, searchHistoryFragment = SearchHistoryFragment.newInstance());
        ft.commit();


        searchHistoryFragment.setOnClickItemListener(new SearchHistoryFragment.OnClickItemListener() {
            @Override
            public void onClickItem(MovieBean data) {
                if (data == null) {
                    return;
                }
                etSearchInput.setText(data.getName());
                search();
            }
        });

        searchListFragment.setOnSearchResultListener(new SearchListFragment.OnSearchResultListener() {
            @Override
            public void onSearchResult(MovieBean bean) {
                if (bean == null) {
                    return;
                }
                searchHistoryFragment.updateHistory(bean);
            }
        });
    }

    @Override
    public void onClick(View view) {
        int id = view.getId();
        if (id == R.id.ll_title_back_box) {
            finish();
        } else if (id == R.id.ll_search_clear) {
            etSearchInput.setText("");
        } else if (id == R.id.tv_search_submit) {
            search();
        }
    }

    /**
     * 获取输入的数据开始搜索
     */
    private void search() {
        String search = etSearchInput.getText().toString();
        if (StringUtil.isEmpty(search)) {
            return;
        }
        etSearchInput.clearFocus();
        InputMethodManager imm =
                (InputMethodManager)
                        getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(etSearchInput.getWindowToken(), 0);
        Bundle bundle = new Bundle();
        bundle.putString("searchText", search);
        searchListFragment.setArguments(bundle);
        // 隐藏搜索历史
        flSearchHistory.setVisibility(View.GONE);
    }
}
